<template>
    <div v-loading="loading" style="width: 100%">
        <SavePage :title="pageDisabled ? `${form.taskNumber}-记录结果` : `施工点专项巡查记录表`">
            <template v-if="pageDisabled" slot="title">
                <span>巡查类型：施工点专项检查</span>
            </template>
            <template slot="buttons">
                <BaseButton :loading="submitLoading" @click="handleSubmit">保存</BaseButton>
            </template>
            <template slot="body">
                <TitleTips v-if="pageDisabled" title="施工点专项检查情况记录表" :required="true" />
                <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="110px">
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="检查部门" prop="deptIds">
                                <OrgSelect :is-filter="true" :value.sync="form.deptIds" :name.sync="form.deptName" :disabled="pageDisabled" @change="form.inspectUsers = []" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="路线名称" prop="highwayCode">
                                <RoadSelect
                                    :value.sync="form.highwayCode"
                                    :name.sync="form.highwayName"
                                    :stake.sync="form.stake"
                                    :disabled="pageDisabled"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="方向" prop="direction">
                                <el-select v-model="form.direction" clearable placeholder="请选择" style="width: 100%" @change="getDirectionName">
                                    <el-option v-for="m in directionOptions" :key="m.value" :label="m.label" :value="m.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <!-- <el-form-item label="关联养护类型" prop="hasMain">
                                <el-select v-model="form.hasMain" clearable placeholder="请选择" style="width: 100%" @change="hasMainChange">
                                    <el-option v-for="m in booleanOptions" :key="m.value" :label="m.label" :value="m.value" />
                                </el-select>
                            </el-form-item> -->
                            <el-form-item label="关联养护类型" prop="associatedMaintType">
                                <el-select v-model="form.associatedMaintType" clearable placeholder="请选择" style="width: 100%" @change="hasMainChange">
                                    <el-option v-for="m in CorrelationTypeOptions" :key="m.value" :label="m.label" :value="m.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="form.associatedMaintType === 2" :xl="6" :lg="8">
                            <el-form-item label="养护任务单" prop="associatedMaintId">
                                <el-select
                                    v-model="form.associatedMaintId"
                                    :disabled="mainDisabled"
                                    multiple
                                    filterable
                                    clearable
                                    :placeholder="mainDisabled ? '请先选择路线名称和方向' : '请选择'"
                                    style="width: 100%"
                                    @visible-change="handleSelectTask"
                                    @remove-tag="handleSelectTask"
                                    @clear="currentMain = []"
                                >
                                    <el-option v-for="m in taskOptions" :key="m.value" :label="m.label" :value="m.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col v-if="form.associatedMaintType === 3" :xl="6" :lg="8">
                            <el-form-item label="养护工程" prop="associatedMaintId">
                                <el-select
                                    v-model="form.associatedMaintId"
                                    :disabled="mainDisabled"
                                    multiple
                                    filterable
                                    collapse-tags
                                    clearable
                                    :placeholder="mainDisabled ? '请先选择路线名称和方向' : '请选择'"
                                    style="width: 100%"
                                    @visible-change="handleSelectMain"
                                    @remove-tag="handleSelectMain"
                                    @clear="currentMain = []"
                                >
                                    <el-option v-for="m in maintOptions" :key="m.value" :label="m.label" :value="m.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :xl="6" :lg="8">
                            <el-form-item label="巡查日期" prop="inspectDate">
                                <el-date-picker
                                    v-model="form.inspectDate"
                                    type="date"
                                    placeholder="请选择"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="巡查时段" prop="time">
                                <el-time-picker
                                    v-model="form.time"
                                    is-range
                                    size="small"
                                    format="HH:mm"
                                    value-format="HH:mm"
                                    :editable="false"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="巡查人员" prop="inspectUsers">
                                <UserSelect :id="deptId" :multiple="true" :value.sync="form.inspectUsers"></UserSelect>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="负责人" prop="principal">
                                <UserSelect :is-all="true" :value.sync="form.principal"></UserSelect>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <CardList
                    ref="cardList"
                    :has-main="form.associatedMaintType !== 1"
                    :main-info="currentMain"
                    :road-info="{ highwayCode: form.highwayCode, direction: form.direction, directionName: form.directionName, stake: form.stake }"
                ></CardList>
            </template>
        </SavePage>
    </div>
</template>

<script>
import { InspectionRecordModel, MaintenanceProjectModel, MaintenanceTaskModel } from '@/models'
import { DirectionTwoWayOptions, BooleanOptions } from '@/config/constants'
import CardList from './components/CardList.vue'
import { CorrelationTypeOptions } from '@/views/maintenance-decision/constants'
import { uniqueId } from 'lodash-es'

export default {
    name: 'AddRoadworkTask',
    components: {
        CardList
    },
    data() {
        return {
            CorrelationTypeOptions,
            model: new InspectionRecordModel(),
            booleanOptions: BooleanOptions,
            directionOptions: DirectionTwoWayOptions,
            maintenanceProjectModel: new MaintenanceProjectModel(),
            maintenanceTaskModel: new MaintenanceTaskModel(),
            loading: false,
            submitLoading: false,
            number: '',
            form: {
                deptIds: [],
                // time: [], // 加了默认数组会导致选择卡顿
                inspectUsers: [],
                associatedMaintType: 1,
                associatedMaintId: []
            },
            rules: {
                deptIds: [{ required: true, message: '请选择检查部门', trigger: 'change' }],
                highwayCode: [{ required: true, message: '请选择路线名称', trigger: 'change' }],
                direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
                inspectDate: [{ required: true, message: '请选择巡查日期', trigger: 'change' }],
                time: [{ required: true, message: '请选择巡查时段', trigger: 'change' }],
                inspectUsers: [{ required: true, message: '请选择巡查人员', trigger: 'change' }],
                principal: [{ required: true, message: '请选择负责人', trigger: 'change' }],
                associatedMaintType: [{ required: true, message: '请选择关联养护类型', trigger: 'change' }],
                associatedMaintId: [{ required: true, message: '请选择', trigger: 'change' }]
            },
            maintOptions: [],
            taskOptions: [],
            currentMain: null
        }
    },
    computed: {
        deptId() {
            return this.form.deptIds[this.form.deptIds.length - 1]
        },
        pageDisabled() {
            return !(this.$route.query.pageType === 'record')
        },
        mainDisabled() {
            return !(this.form.highwayCode && this.form.direction)
        }
    },
    watch: {
        'form.highwayCode'(newValue) {
            if (newValue && this.form.direction) {
                this.getMainList()
                this.getTaskList()
            }
        },
        'form.direction'(newValue) {
            if (newValue && this.form.highwayCode) {
                this.getMainList()
                this.getTaskList()
            }
        }
    },
    created() {
        // 合并url上传递的参数
        const query = this.$route.query
        query.deptIds = query.deptIds ? query.deptIds.toString().split(',').map(Number) : []
        query.type = Number(query.type)
        this.form = Object.assign(this.form, query)
    },
    methods: {
        // 获取当前公路和方向，进行中的养护工程列表
        getMainList() {
            const data = {
                status: 1, // 只要进行中状态的
                roadCode: this.form.highwayCode,
                direction: this.form.direction,
                pageSize: 1000
            }
            this.maintenanceProjectModel.getList(data).then((res) => {
                this.maintOptions = res.list.map((item) => {
                    return {
                        ...item,
                        value: item.id,
                        label: item.projectName
                    }
                })
                // 每次获取新的数据后，清空当前的选中工程
                this.form.associatedMaintId = []
                this.currentMain = []
            })
        },
        getTaskList() {
            const data = {
                statusList: [6], // 只要进行中状态的
                highwayCode: this.form.highwayCode,
                direction: this.form.direction,
                pageSize: 1000
            }
            this.maintenanceTaskModel.getList(data).then((res) => {
                this.taskOptions = res.list.map((item) => {
                    return {
                        ...item,
                        value: item.id,
                        label: item.itemName
                    }
                })
                // 每次获取新的数据后，清空当前的选中工程
                this.form.associatedMaintId = []
                this.currentMain = []
            })
        },
        hasMainChange() {
            this.form.associatedMaintId = []
            this.currentMain = []
        },
        handleSelectTask() {
            const value = this.form.associatedMaintId
            console.log(value)
            const arr = []
            value.forEach(item => {
                const currentTask = this.taskOptions.find((m) => m.value === item) || {}
                console.log(currentTask)
                arr.push({
                    fid: uniqueId(),
                    facilityCode: currentTask.facilityName,
                    facilityName: currentTask.facilitiesName,
                    // lngLatList: currentTask.facilityLngLat,
                    locationType: Number(currentTask.maintainPlace),
                    stake1: currentTask.stakeNo ? currentTask.stakeNo.split('+')[0].replace('K', '') : null,
                    stake2: currentTask.stakeNo ? currentTask.stakeNo.split('+')[1].replace('K', '') : null,
                    startStake1: currentTask.startStakeNo ? currentTask.startStakeNo.split('+')[0].replace('K', '') : null,
                    startStake2: currentTask.startStakeNo ? currentTask.startStakeNo.split('+')[1].replace('K', '') : null,
                    endStake1: currentTask.endStakeNo ? currentTask.endStakeNo.split('+')[0].replace('K', '') : null,
                    endStake2: currentTask.endStakeNo ? currentTask.endStakeNo.split('+')[1].replace('K', '') : null
                })
            })
            this.currentMain = arr
            console.log(arr)
        },
        // 选择对应养护工程后，把信息传递给缺陷表
        handleSelectMain() {
            const value = this.form.associatedMaintId
            const arr = []
            value.forEach(item => {
                const currentMain = this.maintOptions.find((m) => m.value === item) || {}
                console.log(currentMain)
                const main = {
                    locationType: currentMain.locationType,
                    stake1: currentMain.stakeStart ? currentMain.stakeStart.split('+')[0].replace('K', '') : null,
                    stake2: currentMain.stakeStart ? currentMain.stakeStart.split('+')[1].replace('K', '') : null,
                    startStake1: currentMain.stakeStart ? currentMain.stakeStart.split('+')[0].replace('K', '') : null,
                    startStake2: currentMain.stakeStart ? currentMain.stakeStart.split('+')[1].replace('K', '') : null,
                    endStake1: currentMain.stakeEnd ? currentMain.stakeEnd.split('+')[0].replace('K', '') : null,
                    endStake2: currentMain.stakeEnd ? currentMain.stakeEnd.split('+')[1].replace('K', '') : null
                }
                // 当是设施1时，需要循环处理
                if (currentMain.locationType === 1) {
                    const list = JSON.parse(currentMain.facilityCode)
                    list.forEach((code, index) => {
                        console.log(code)
                        arr.push({
                            fid: uniqueId(),
                            facilityCode: code,
                            // facilityCode: [1, 'S12SYNZTGS0024'],
                            facilityName: currentMain.facilityName.split(',')[index],
                            lngLatList: currentMain.facilityLngLat[index],
                            ...main
                        })
                    })
                } else {
                    arr.push({
                        fid: uniqueId(),
                        ...main
                    })
                }
            })
            this.currentMain = arr
            console.log(arr)
        },
        handleValidate() {
            return new Promise((resolve, reject) => {
                this.$refs.form.validate((vailda) => {
                    resolve(vailda)
                })
            })
        },
        async handleSubmit() {
            this.submitLoading = true
            // 基础表单验证结果
            const formInfoValidate = await this.handleValidate()
            // 缺陷卡片验证结果
            const cardListValidate = await this.$refs.cardList.handleValidate()
            if (formInfoValidate && cardListValidate) {
                const cardListData = this.$refs.cardList.getData()
                let associatedMaintId = null
                let associatedMaintName = null
                // 根据选中的任务单或者工程，处理拼接对应中文名
                if (this.form.associatedMaintId) {
                    associatedMaintId = this.form.associatedMaintId.toString()
                    const list = []
                    let options = []
                    if (this.form.associatedMaintType === 2) { options = this.taskOptions }
                    if (this.form.associatedMaintType === 3) { options = this.maintOptions }
                    this.form.associatedMaintId.forEach(item => {
                        const target = options.find(m => m.value === item)
                        if (target) { list.push(target.label) }
                    })
                    associatedMaintName = list.toString()
                }
                const data = {
                    ...this.form,
                    associatedMaintId,
                    associatedMaintName,
                    deptIds: this.form.deptIds.toString(),
                    inspectUsers: this.form.inspectUsers.toString(),
                    inspectTime: this.form.time.join('~'),
                    resultContent: cardListData
                }
                this.model
                    .saveOrUpdate(data)
                    .then(() => {
                        this.$message({
                            type: 'success',
                            message: '操作成功！',
                            duration: 500,
                            onClose: () => {
                                this.$router.go(-1)
                            }
                        })
                    })
                    .finally(() => {
                        this.submitLoading = false
                    })
            } else {
                this.submitLoading = false
            }
        },
        // 获取方向中文名，用于传递给机电设备弹框查询机电
        getDirectionName(val) {
            const currentDirection = this.directionOptions.find((item) => item.value === val) || {}
            this.form.directionName = currentDirection.label
        }
    }
}
</script>
<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}
.device {
    min-width: 100px;
    height: 32px;
}
</style>
